#pragma once

#include <iostream>
#include <string>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "err.h"
using namespace std;



class udpClient{
  public:
    //初始化的是服务器的套接字
    udpClient(const string& ip, const uint16_t& port)
      :_ip(ip)
      ,_port(port)
      ,_sock(-1)
      {}
    void InitClient(){
      //创建套接字
      _sock = socket(AF_INET, SOCK_DGRAM, 0);
      //不需要绑定，服务器是被动的，不会主动找客户端，当客户端打开时，服务器就能找到客户端了。
     if(_sock==-1)
     {
        //创建失败，打印相应错误信息
        cerr<<"socket error:"<<errno<<": "<<strerror(errno)<<endl;
        exit(SOCKET_ERR);
     }
     cout<<"socket success: "<<_sock<<endl;
    }
 
    void Start(){
        struct sockaddr_in peer;
        memset(&peer,0,sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port =htons(_port);
        peer.sin_addr.s_addr = inet_addr(_ip.c_str());
      while(true){
        //发送
        std::string msg;
        std::cout<<"please enter #";
        getline(cin,msg);
        if(msg == "quit"){
          break;
        }
        msg += '\0';
        sendto(_sock, msg.c_str(), msg.size(), 0, (struct sockaddr *)&peer, sizeof(peer)); //获取用户输入
        char buffer[2048];
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        int n=recvfrom(_sock, buffer, sizeof(buffer)-1, 0,(struct sockaddr *)&temp,&len);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout <<"server echo#"<<buffer << std::endl;
        }
      }
      
    }
    
    ~udpClient(){
 
    }
 
  
  private:
    std::string _ip;//IP地址
    int _port;//端口号
    int _sock;//创建套接字返回的文件描述符

};